package com.cyc.volatileT;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 不保证原子性
 */
public class vDemo {
    // volatile不保证原子类
    // 原子类的Integer
    private volatile static AtomicInteger num = new AtomicInteger();

    public static void add(){
        //+1 操作 调用底层CAS 效率高
        num.getAndIncrement();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 10000; j++) {
                    add();
                }
            }).start();
            //可保证结果正常
//            while (Thread.activeCount()>2){
//                Thread.yield();
//            }
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println("sum "+num);
    }
}
